#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include <stdint.h>
#include <amqp_tcp_socket.h>
#include <amqp.h>
#include <amqp_framing.h>

#include <assert.h>
#include <pthread.h>
#include "utils.h"

#include <pthread.h>

#include "cJSON.h"
#include <termios.h>
#include <sys/types.h>

#include <sys/stat.h>
#include <fcntl.h>

#include <stdio.h>

char* s_hostname;
int s_port;
char* s_exchange;
char* s_bindingkey;
char* s_vhost;
char* s_user;
char* s_pwd;

char* r_hostname;
int r_port;
char* r_exchange;
char* r_bindingkey;
char* r_vhost;
char* r_user;
char* r_pwd;

int config_parse(char * file_path){
	
	struct stat statbuf;
    stat(file_path,&statbuf);
    int file_size=statbuf.st_size;
	char *data;

	FILE *file = fopen(file_path,"rb");

	if(file_size ==0 ||file==NULL){
		printf("Read config file error:%s\n",file_path);
		return -1;
	}
	data = malloc(file_size);
	fread(data,file_size,1,file);
	fclose(file);

	cJSON *config=NULL;
	config = cJSON_Parse(data);
	if(!config){
		printf("parse json config error");
		return -1;
	}
	cJSON *send_config = cJSON_GetObjectItem(config,"send_config");
	if(send_config->type==cJSON_Object){
			s_hostname = cJSON_GetStringValue(cJSON_GetObjectItem(send_config, "hostname"));
			s_port = (int)cJSON_GetNumberValue(cJSON_GetObjectItem(send_config, "port"));
			s_exchange = cJSON_GetStringValue(cJSON_GetObjectItem(send_config, "exchange"));
			s_bindingkey = cJSON_GetStringValue(cJSON_GetObjectItem(send_config, "bindingkey"));
			s_vhost = cJSON_GetStringValue(cJSON_GetObjectItem(send_config, "virtualhost"));
			s_user = cJSON_GetStringValue(cJSON_GetObjectItem(send_config, "user"));
			s_pwd = cJSON_GetStringValue(cJSON_GetObjectItem(send_config, "password"));

	}else{
		printf("parse json config error");
		return -1;
	}

	cJSON *recevie_config = cJSON_GetObjectItem(config,"receive_config");
	if(send_config->type==cJSON_Object){
			r_hostname = cJSON_GetStringValue(cJSON_GetObjectItem(recevie_config, "hostname"));
			r_port = (int)cJSON_GetNumberValue(cJSON_GetObjectItem(recevie_config, "port"));
			r_exchange = cJSON_GetStringValue(cJSON_GetObjectItem(recevie_config, "exchange"));
			r_bindingkey = cJSON_GetStringValue(cJSON_GetObjectItem(recevie_config, "bindingkey"));
			r_vhost = cJSON_GetStringValue(cJSON_GetObjectItem(recevie_config, "virtualhost"));
			r_user = cJSON_GetStringValue(cJSON_GetObjectItem(recevie_config, "user"));
			r_pwd = cJSON_GetStringValue(cJSON_GetObjectItem(recevie_config, "password"));

	}else{
		printf("parse json config error");
		return -1;
	}
		
	
	free(data);
	return 0;
}
